package com.example.teadoctor;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{


    //底部按钮点击事件
    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        //底部按钮跳转(默认情况下，没有任何item被选中，就不会触发onNavigationItemSelected方法，也就不会执行任何操作)
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_headlines:
                    getSupportFragmentManager().beginTransaction().replace(R.id.frame, new HeadlinesFragment()).commit();
                    return true;
                case R.id.navigation_know:
                    getSupportFragmentManager().beginTransaction().replace(R.id.frame, new KnowFragment()).commit();
                    return true;
                case R.id.navigation_consult:
                    getSupportFragmentManager().beginTransaction().replace(R.id.frame, new ConsultFragment()).commit();
                    return true;
                case R.id.navigation_operate:
                    getSupportFragmentManager().beginTransaction().replace(R.id.frame, new OperateFragment()).commit();
                    return true;
                case R.id.navigation_data:
                    getSupportFragmentManager().beginTransaction().replace(R.id.frame, new DataFragment()).commit();
                    return true;
            }
            return true;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //检查是否联网
        boolean isNetwork=isNetworkAvailable(this);
        if (!isNetwork) {
            Toast.makeText(getApplicationContext(), "设备没有联网" , Toast.LENGTH_SHORT).show();
        }
        setContentView(R.layout.activity_main);


        //底部按钮
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);


        //设置导航栏
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        getSupportFragmentManager().beginTransaction().replace(R.id.frame, new HeadlinesFragment()).commit();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        Intent intent=new Intent();

        // Handle the  action，侧边栏按钮点击页面跳转
        switch (id) {
            case R.id.nav_search:
                intent.setComponent(new ComponentName(MainActivity.this,Search.class));
                startActivity(intent);
                return true;
            case R.id.nav_collections:
                intent.setComponent(new ComponentName(MainActivity.this,Collections.class));
                startActivity(intent);
                return true;
            case R.id.nav_share:
                sharePage();
                return true;
            case R.id.nav_opinions:
                intent.setComponent(new ComponentName(MainActivity.this,Opinions.class));
                startActivity(intent);
                return true;
            case R.id.nav_records:
                intent.setComponent(new ComponentName(MainActivity.this,Records.class));
                startActivity(intent);
                return true;
            case R.id.nav_version:
                intent.setComponent(new ComponentName(MainActivity.this,Version.class));
                startActivity(intent);
                return true;
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return false;
    }

    //分享到其他应用
    private void sharePage() {

        Intent shareIntent = new Intent(Intent.ACTION_SEND); // 创建一个ShareIntent对象
        shareIntent.setType("text/plain"); // 设置分享内容的类型
        shareIntent.putExtra(Intent.EXTRA_TEXT, "茶博士app，最新最全的茶信息都在这"); // 设置分享的文本内容
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 添加标志，防止出现ActivityNotFoundException错误
        shareIntent.addCategory(Intent.CATEGORY_DEFAULT); // 添加默认的分享类型
        startActivity(Intent.createChooser(shareIntent, "要分享到")); // 启动系统的分享对话框
        /*
        //Android7.0及以上的版本不允许在应用之间共享file://类型的Uri，因为存在安全隐患。
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("image/*");
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.logo);
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "share_image.jpg");
        FileOutputStream fo;
        try {
            file.createNewFile();
            fo = new FileOutputStream(file);
            fo.write(bytes.toByteArray());
            fo.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            Uri imageUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", file);
            shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
            shareIntent.putExtra(Intent.EXTRA_TEXT, "茶博士app");
            startActivity(Intent.createChooser(shareIntent, "分享"));
        }catch (Exception e) {
            e.printStackTrace();
        }
        */
    }

    //检测设备是否联网
    private boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo info = cm.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                return true;
            }
        }
        return false;
    }
}
